/**
 * @author tshepo
 *
 */
package fr.toto.triseries;

import java.awt.AWTException;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.plaf.synth.SynthLookAndFeel;

import com.kokotchy.betaSeriesAPI.UtilsXml;
import com.kokotchy.betaSeriesAPI.api.xmlImpl.BetaSerieApi;
import com.kokotchy.betaSeriesAPI.model.Episode;
import com.kokotchy.betaSeriesAPI.model.SubtitleLanguage;
import com.sun.net.httpserver.HttpServer;

import fr.toto.constantes.Constantes;
import fr.toto.exceptions.ProcessException;
import fr.toto.files.AccesFile;
import fr.toto.files.WatchDir;
import fr.toto.menuitem.MyPopupMenu;
import fr.toto.subtitles.Soutitre;
import fr.toto.subtitles.SoutitreSet;
import fr.toto.webui.MyHandler;

public class Main implements Constantes {

	public static DetailFile af;
	public static String token;
	private static TrayIcon trayIcon;
	private final static ScheduledExecutorService scheduler = Executors
			.newScheduledThreadPool(1);

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			if (Files.exists(LOOKXMLPATH)) {
				SynthLookAndFeel synth = new SynthLookAndFeel();
				synth.load(LOOKXMLPATH.toUri().toURL());
				UIManager.setLookAndFeel(synth);
			} else

				UIManager.setLookAndFeel(UIManager
						.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			new ProcessException(e);
		}

		BetaSerieApi.setApiKey(APIKEY);

		UtilsXml.setUserAgent(PGMNAME + "." + VERSION + " - "
				+ System.getProperty("os.name").toString());

		if (!SystemTray.isSupported()) {
			JOptionPane.showMessageDialog(null,
					MESSAGES.getString("ErrorSupportSysTrayMsg"));
		} else {

			trayIcon = new TrayIcon(iconBusy, PGMNAME);
			trayIcon.setImageAutoSize(true);
			try {
				SystemTray.getSystemTray().add(trayIcon);
			} catch (AWTException e1) {
				JOptionPane.showMessageDialog(
						null,
						MESSAGES.getString("ErrorSupportSysTrayMsg")
								+ e1.toString());
			}
			if (Reglages.Init()) {

				UtilsXml.setUserAgent(PGMNAME + "." + VERSION + " - "
						+ System.getProperty("os.name").toString() + " - "
						+ Reglages.getUser());

				af = new DetailFile();

				BetaSeriesQuery.iniSeriesSet();

				BetaSeriesQuery.InitEpisodeSet();

				final MyPopupMenu ppm = new MyPopupMenu();
				trayIcon.setImage(iconWait);

				trayIcon.addMouseListener(new MouseAdapter() {
					@Override
					public void mousePressed(MouseEvent e) {
						if (e.isPopupTrigger()
								|| e.getButton() == MouseEvent.BUTTON3) {
							ppm.generateMenu();
							ppm.setLocation(e.getX(), e.getY());
							ppm.setInvoker(ppm);
							ppm.setVisible(true);
						}
					}
				});

				SoutitreSet.Load();
				for (Object s : SoutitreSet.ListATraiter()) {
					if (s instanceof Soutitre) {
						af.executer((Soutitre) s);
					}
				}
				af.executer(new Soutitre("", 0, 0, SubtitleLanguage.UNKNOWN, ""));

				UpdateSeries us = new UpdateSeries(af);
				scheduler.scheduleAtFixedRate(us, 6, 6, TimeUnit.HOURS);

				for (Object ep : EpisodesSet.ListATraiter()) {
					if (ep instanceof Episode)
						if (!((Episode) ep).isDownloaded()) {
							Path file = AccesFile.Find((Episode) ep);
							if (file != null) {
								BetaSeriesQuery.setDownloaded((Episode) ep);
								((Episode) ep).setDownloaded(true);
							}
						}
				}

				if (Reglages.SERVEUR) {
					InetSocketAddress addr = new InetSocketAddress(
							Reglages.PORT);
					HttpServer server;
					try {
						server = HttpServer.create(addr, 0);
						server.createContext("/", new MyHandler());
						server.setExecutor(Executors.newCachedThreadPool());
						server.start();
					} catch (IOException e1) {
						new ProcessException(e1);
					}
				}

				try {
					WatchDir w = new WatchDir(Reglages.GetDirsToScan(),
							Reglages.isRecursiveScan(), af);
					new Thread(w).start();
				} catch (IOException e) {
					new ProcessException(e);
				}

				System.out.println("fin");

			}
		}

	}

	public static Properties MenuProperties() {
		Properties p = new Properties();
		try {
			if (Files.exists(MENUTXTPATH)) {
				p.load(new InputStreamReader(new FileInputStream(MENUTXTPATH
						.toString()), CharsetName));
			} else {
				p.load(new InputStreamReader(Main.class
						.getResourceAsStream("/fr/toto/menuitem/menu.txt"),
						CharsetName));
			}
		} catch (Exception e) {
			new ProcessException(e);
		}
		return p;
	}
}
